<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left"  :title="$t('translationImage.adjustmentWarehouse')"  @clickRight="clickRight" scanType="1"></nav-bar-custom>
		</template>
		
		<template v-slot:gBody>
			<view class="barcodeSplitting" :style="'height: calc(100vh - '+ navHeight +'px);'">
				<!-- 扫描和库位选择模块 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{$t('distributedEnter.barcodeScan')}}
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('warehousing.libraryBitCode')
						}}：</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.locationCodes"
							:placeholder="$t('warehousing.scanLocation')" @blur="data.focus=false"  :focus="data.focus" @confirm="confirmLocation"
							@iconClick="iconClickLocation">
						</uni-easyinput>
					</view>
					<view v-if="data.isCapacityBool" class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{$t('stockManage.purposeSeat')}}：</text>
						<storageBin ref="storageBinRef" v-model="data.locationId" :ignoreLocationCode="data.ignoreLocationCode" class="gui-text-right" requestUrl="/wms/wmsLocationCapacity/getLocationByWarehouseCodeForCCP" :placeholder="$t('distributedEnter.placeholderTextChoose')" :requestParam="data.requestParam" @setClick="getClick"></storageBin>
					</view>
					<view v-else class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{$t('stockManage.purposeSeat')}}：</text>
						<comboGrid ref="comboGridRef" v-model="data.locationId" :requestParam="data.requestParam" requestUrl="/wms/wmsLocationCapacity/getLocationByWarehouseCodeForCCP"  :placeholder="$t('distributedEnter.placeholderTextChoose')" inputKey="locationCode"  :column="data.columnRule.column" bindValue="locationName" @setClick="getRuleClick"></comboGrid>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;"><text
							class="required-color">*</text>{{$t('distributedEnter.barcodeScan')}}</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan2" v-model="data.barcode"  @focus="data.focus=false" :focus="!data.focus" type="search"
							@confirm="confirm" @iconClick="iconClick" :placeholder="$t('stockManage.pleaseScanCode')">
						</uni-easyinput>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0">
                		<text class="item-info-title" >{{$t('translationImage.warehouseSubordinate')}}：</text>
						<input type="text" 
							disabled
							style="margin: 8rpx 0;text-align: right;"
							class="gui-form-input" 
							v-model="data.warehouseCode" 
							:placeholder="$t('pageTranslation.bringFromBarcode')" />
             		</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title">{{$t('translationImage.currentLocation')}}：</text>
						<input type="text" 
							disabled
							style="margin: 8rpx 0;text-align: right;"
							class="gui-form-input" 
							v-model="data.currentLocationCode" 
							:placeholder="$t('pageTranslation.bringFromBarcode')" />
					</view>
				</view>
				<!-- card模块 -->
				<!-- <scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll"> -->
					<view v-if="data.scanInfo" class="custom-form-card">
						<uni-collapse v-model="data.value">
							<uni-collapse-item titleBorder="none" :show-animation="true">
								<template v-slot:title>
									<view class="custom-card-title">
										<text class="title-line"></text>
										{{$t('distributedOut.atPresent')}}
									</view>
								</template>
								<view class="content">
									<view class="custom-card-itemOne">
										<text class="item-info-title">{{$t('distributedEnter.materialCoded')}}：</text>{{ data.scanInfo.barcode }}
									</view>
									<view class="custom-card-itemOne">
										<view class="card-item-50">
											<text class="item-info-title">{{$t('distributedEnter.materialCode')}}：</text>{{ data.scanInfo.materialCode }}
										</view>
										<view class="card-item-50">
											<text class="item-info-title">{{$t('distributedEnter.materialName')}}：</text>{{ data.scanInfo.materialName }}
										</view>
									</view>
									<view class="custom-card-itemOne">
										<text class="item-info-title">{{$t('distributedEnter.materialSpec')}}：</text>{{ data.scanInfo.materialSpec }}
									</view>
									<view class="custom-card-itemOne">
										<view class="card-item-50">
											<text class="item-info-title">{{$t('pageTranslation.currentNumbers')}}：</text>{{ data.scanInfo.currentQty }}
										</view>
										<view class="card-item-50">
											<text class="item-info-title">{{$t('distributedEnter.uom')}}：</text>{{ data.scanInfo.unit }}
										</view>
									</view>
								</view>
							</uni-collapse-item>
						</uni-collapse>
					</view>
				<!-- </scroll-view> -->

				<!-- 底部确定按钮 -->
				<view class="page-bottom-box"><view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelCommit">{{$t('calendar.submit')}}</view></view>
				<uni-popup ref="alertDialog" type="dialog">
					<uni-popup-dialog :type="data.msgType" :cancelText="$t('translationImage.close')" :confirmText="$t('pageTranslation.toSet')" :title="$t('smashRemoval.warmPrompt')" content="当前未设置默认仓库，请前往设置" @confirm="dialogConfirm"></uni-popup-dialog>
				</uni-popup>
			</view>
		</template>
	</gui-page>
</template>

<script setup>
	import {navigate, navigateBack} from '@/utils/routerSkip.js';
	import pdaScan from '@/hooks/pdaScan.js'
	import { useStore } from "vuex";
	import { DEFAULT_WAREHOUSECODE } from '@/constant/index.js'
	import { getDataDictionaryFn } from '@/utils/index.js'
	import storageBin from '@/components/storageBin.vue'
	import comboGrid from '@/components/comboGrid.vue'
	import { onShow } from '@dcloudio/uni-app';
	import { basPdaOperationLogFn } from '@/utils/index.js';
	import { OPERATION_COMMIT, OPERATION_SCAN } from '@/constant/index.js'
	import { houseLocationChange,wmsSelectWmsBarcodeInfo,checkLocation } from '@/api/api.js'
	import {
		ref,
		reactive,
		onMounted,
		watch,
		computed,
		toRaw
	} from 'vue';

	//JS国际化引入
	import { useI18n } from 'vue-i18n';
	const { t } = useI18n();

	components: {
		storageBin,
		comboGrid
	}
	const storageBinRef = ref(null)
	const comboGridRef = ref(null)
	let store = useStore();
	const navHeight = computed(() => {
		return store.state.navHeight
	})
	const { scan } = pdaScan()
	let alertDialog = ref(null)
	let data=reactive({
		isCapacityBool:false,// 是否带容量 默认为false
		msgType:'warn',
		value: ['0'],
		warehouseCode:uni.getStorageSync(DEFAULT_WAREHOUSECODE) || '',// 设置的默认仓库
		barcode:'', //条码
		barcodeList:[],//条码数组
		warehouseName:'', //所属仓库,
		currentLocationCode:'', //当前库位
		// objectiveSeat:'',//目的库位
		ignoreLocationCode:[], //前端算满的库位
		scanInfo:undefined,// 当前扫码
		locationId:'',//目的库位id
		requestParam:{
			warehouseCode:uni.getStorageSync(DEFAULT_WAREHOUSECODE) || '',// 设置的默认仓库
		},
		locationUseList:[],
		columnRule:{
			column: [{
				label: t('distributedOut.location'),
				name: "locationCode",
			}]
		},
		locationName:'',// 选中库位
		locationCodes: '',
		currentLocationInfo:{},
		focus:true
		
	})
	onShow( async () => {
	    data.warehouseCode = uni.getStorageSync(DEFAULT_WAREHOUSECODE) || ''
		data.requestParam.warehouseCode = uni.getStorageSync(DEFAULT_WAREHOUSECODE) || ''
		if(!data.warehouseCode.length){
			alertDialogOpen()
		}
	})
	onMounted(()=>{
		uni.$on('scancodedate', (itme) => {
			console.log('获取到的code：' + itme.code,data.focus)
			if(data.focus){
				getCodeLocation(itme.code, 'pda')
			}
			if(data.focus==false){
				getCode(itme.code, 'pda')
			}
		})
		
	})
	const filter = async ()=>{
		// 查询目的仓库
		let locationCapacity = await getDataDictionaryFn('LocationCapacity')
		console.log(locationCapacity,'----tepSelect1------')
		let bool = locationCapacity.some((item)=>{
			return item.value == data.warehouseCode
		})
		data.isCapacityBool = bool
		// if(bool){
		// 	data.columnRule = {
		// 		column: [{
		// 				label: "库位名",
		// 				name: "locationCode",
		// 		},{
		// 				label: "库位容量",
		// 				name: "maxCapacity",
		// 		}]
		// 	}
		// }else{
		// 	data.columnLocation = {
		// 		column: [{
		// 				label: "库位名",
		// 				name: "locationCode",
		// 		}]
		// 	}
		// }
	}
	watch(()=>data.warehouseCode, (newVal, oldVal) => {
		filter()
	}, {
		immediate: true,
		deep: true
	});
	const alertDialogOpen = () =>{
		// 延迟疫苗调用用以解决弹框bug
		// setTimeout(()=>{
		// 	alertDialog.value.open();
		// },500)
		
		uni.showModal({
			content: t('pageTranslation.noDefaultLocation'),
			showCancel: false,
			title:t('smashRemoval.warmPrompt'),
			confirmText:t('pageTranslation.toSet'),
			success: function (res) {
					if (res.confirm) {
						 uni.navigateTo({
						 url: '/pages/setting/warehouse'
						 })
					} else if (res.cancel) {
						
					}
				}
		});
	}
	const dialogConfirm = ()=>{
		alertDialog.value.close();
		navigate({
			url: '/pages/setting/warehouse'
		})
	}
	// 计算库位逻辑
	const calculateLocationCode = (newVal) => {
		let tepData = toRaw(newVal)
		if(!tepData.length){
			data.scanInfo = undefined
			data.warehouseName = ''
			data.currentLocationCode = ''
		}
		if(!data.scanInfo && tepData.length){
			data.scanInfo = tepData[0]
			data.warehouseName = tepData[0].warehouseName
			data.currentLocationCode = tepData[0].locationCode
		}
		// 先清空,后续追加
		data.locationUseList.forEach(l=>{
			l.barcodeList = []
		})
		// 追加
		tepData.forEach(x=>{
			data.locationUseList.forEach(k=>{
				if(x.locationId == k.locationCode){
					k.barcodeList.push(x.barcode)
					k.surplusCapacity = k.currentCapacity - k.barcodeList.length
				}
			})
		})
		if(!data.isCapacityBool) return
		//算满库位变量置空
		data.ignoreLocationCode = []
		// 把前端预算容量算出为0的库位抽出
		data.locationUseList.forEach(x=>{
			if(x.surplusCapacity == 0){
				data.ignoreLocationCode.push(x.locationCode)
			}
		})
	}
	data.barcodeList = computed(() => {
		return store.state.warehouseChangeList
	})
	//把扫描条码变为物料集合的二维数组
	watch(()=>data.barcodeList, (newVal, oldVal) => {
		calculateLocationCode(newVal)
	}, {
		immediate: true,
		deep: true
	});

	// 用户调起相机扫码
	const iconClickLocation = async (type) => {
		data.focus=true
		if (type === 'suffix') {
			let code = await scan()
			getCodeLocation(code, 'scan')
		}
	}
	// 用户点击键盘上搜索
	const confirmLocation = () => {
		data.focus=true
		getCodeLocation(data.locationCodes, 'keydown')
	}

	// 获取code
	const getCodeLocation = (code, type) => {
		data.locationCodes = code
		var parmes = {
			warehouseCode: data.warehouseCode,
			locationCode: code,
		}
		checkLocation(parmes).then(res => {
			try {
				let inputParameter = JSON.stringify(parmes)
				let returnParameter = JSON.stringify(res)
				let operationPicture = '库内调整'
				let callInterface = res.rquestUrl
				let opertionParmes = {
					inputParameter,
					returnParameter,
					operationPicture,
					callInterface,
					responseCode: res.status,//返回状态
					errorMessage: res.message,//错误信息
					isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
					operationType: OPERATION_SCAN
				}
				basPdaOperationLogFn(opertionParmes)
			} catch (error) {
			}
			if (res.status == 200 && res.data.residualCapacity != 0) {
				console.log(res.data)
				data.currentLocationInfo = res.data;
				data.locationId = res.data.locationCode;
				data.locationName =  res.data.locationCode
			} else if (res.status == 200 && res.data.residualCapacity == 0) {
				uni.showToast({ title: t('warehousing.capacityLibrary'), icon: "none" });
			}
			else {
				uni.showToast({ title: res.message, icon: "none" });
			}
		})
	}

	// 获取选中的库位id
	const getClick = (x) => {
		data.currentLocationInfo = x;
		data.locationId = x.locationCode;
		data.locationName = x.locationName
	}
	// 获取选中的库位id
	const getRuleClick = (x)=>{
		data.currentLocationInfo = x;
		data.locationId = x.locationCode;
		data.locationName = x.locationName
	}

	// 用户点击扫码图标
	const iconClick = async (type) => {
		data.focus=false
		if (type === 'suffix') {
			let code = await scan()
			if(!data.focus){
				getCode(code, 'scan2')
			}
		}
	}
	// 用户点击搜索
	const confirm = () => {
		data.focus=false
		if(!data.focus){
			getCode(data.barcode,'keydown')
		}
	}

	// 获取code
	const getCode = (code, type) => {
		data.barcode=code
		console.log(code,'---code---')
		// 判断这个托盘本次有没有绑定过
		console.log(data.barcodeList,'data.barcodeList')
		if(!data.locationId){
			uni.showToast({
				title: t('pageTranslation.plsChooseDestination'),
				icon: 'none'
			})
			return
		}
		let isBind = data.barcodeList.some(x=>x.barcode == code);
		if(isBind) {
			uni.showToast({
				title: t('JsInternational.scanned'),
				icon: 'none'
			})
			return
		}
		// 判断当前用户选择的库位有没有容量
		if(data.isCapacityBool && data.ignoreLocationCode.includes(data.locationId)){
			uni.showToast({
				title: t('JsInternational.volumn'),
				icon: 'none'
			})
			return
		}
		if(!code){
			uni.showToast({
				title: t('stockManage.pleaseScanCode'),
				icon: 'none'
			})
			return
		}
		data.scanValue = code
		let parmes = {
			isSp:0,
			barcode: code,
			selectType: 'houseLocationChange',
		}
		wmsSelectWmsBarcodeInfo(parmes).then(res => {
			try {
				let inputParameter = JSON.stringify(parmes)
				let returnParameter = JSON.stringify(res)
				let operationPicture = '库内调整'
				let callInterface = res.rquestUrl
				let opertionParmes = {
					inputParameter,
					returnParameter,
					operationPicture,
					callInterface,
					responseCode:res.status,//返回状态
					errorMessage:res.message,//错误信息
					isPass:res.status == 200 ? 'Y' : 'N',//是否成功 Y N
					operationType:OPERATION_SCAN
				}
				basPdaOperationLogFn(opertionParmes)
			} catch (error) {
			}
			console.log(res)
			if (res.status == 200) {
				if(res.data.locationCode == data.locationId){
					uni.showToast({
						title: t('JsInternational.locationSame'),
						icon: 'none'
					})
					return
				}
				let warehouseCode = uni.getStorageSync(DEFAULT_WAREHOUSECODE) || ''
				if(res.data.warehouseCode != warehouseCode){
					uni.showToast({
						title: t('materials.belongToTheDefault'),
						icon: 'none'
					})
					return
				}
				data.scanInfo = res.data
				data.scanInfo.goaLlocationId = data.currentLocationInfo.locationCode
				data.scanInfo.goalWarehouseCode = data.requestParam.warehouseCode
				data.scanInfo.goalLocationCode= data.currentLocationInfo.locationCode
				data.scanInfo.goalLocationName= data.currentLocationInfo.locationName
				data.warehouseName = res.data.warehouseName
			    data.currentLocationCode = res.data.locationCode
				judgeBarcode()
			} else {
				uni.showToast({ title: res.message, icon: "none" });
			}
		})
	}

	// 判断 Barcode
	const judgeBarcode = () => {
		let isTrue = data.locationUseList.some(x=>x.locationCode === data.locationId)
		if(!isTrue){
			data.locationUseList.push({
				locationCode: data.currentLocationInfo.locationCode, //库位code
				surplusCapacity:  Number(data.currentLocationInfo.maxCapacity) - Number(data.currentLocationInfo.usedInventory), //后端告诉前端容量
				barcodeList:[], //当前库位本次扫描绑定的barcode条码集合
				currentCapacity:Number(data.currentLocationInfo.maxCapacity) - Number(data.currentLocationInfo.usedInventory), //后端容量减去本次扫描绑定条码的剩余容量  前端预算容量
			})
		}
		store.commit('addWarehouseChangeList',data.scanInfo)
	}
	//扫描纪录
	const clickRight = () => {
		navigate({
			url: '/pages/barcodeManagement/adjustmentWarehouseRecord'
		})
	}
	// 提交操作
	const handelCommit = () =>{
		if(!data.warehouseCode.length){
			alertDialogOpen()
			return;
		}
		if(!data.barcodeList.length){
			uni.showToast({
				title: t('stockManage.pleaseScanCode'),
				icon: 'none'
			})
			return
		}
		let tepData = toRaw(data.barcodeList)
		console.log(tepData,'----tepData----')
		// 只会有一个默认仓库 所有默认取扫描数组第一个
		let parmes = {
			wmsBarcodeList:[]
		}
		tepData.forEach(x => {
			parmes.wmsBarcodeList.push({
				id:x.id,// 条码的id
				locationId:x.locationId,//库位id
				oldLocationCode:x.locationCode,//原始库位code
				locationCode:x.goalLocationCode,// 仓库code
				warehouseCode:x.goalWarehouseCode,//仓库code	
				locationName:x.goalLocationName,//库位name
			})
		});
		// 添加加载框
		uni.showLoading({
			title: 'loading',
			mask: true
		});
		houseLocationChange(parmes).then(res => {
			try {
				let inputParameter = JSON.stringify(parmes)
				let returnParameter = JSON.stringify(res)
				let operationPicture = '库内调整'
				let callInterface = res.rquestUrl
				let opertionParmes = {
					inputParameter,
					returnParameter,
					operationPicture,
					callInterface,
					responseCode:res.status,//返回状态
					errorMessage:res.message,//错误信息
					isPass:res.status == 200 ? 'Y' : 'N',//是否成功 Y N
					operationType:OPERATION_COMMIT
				}
				basPdaOperationLogFn(opertionParmes)
			} catch (error) {
			}
			if (res.status == 200) {
				//隐藏加载框
				uni.hideLoading();
				//删除已提交的数据
				data.barcode = '' //置空当前条码
				data.locationCodes=''
				uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: "none" });
				store.commit('reactWarehouseChangeList')
				if(data.isCapacityBool){
					storageBinRef.value.restInitData()
				}else{
					comboGridRef.value.restInitData()
				}
				// navigateBack()
			} else {
				uni.showToast({ title: res.message, icon: "none" });
			}
		})

	}
	
</script>

<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
		// height: 100vh;
}
.distributed-head{
		border-bottom-left-radius: 16rpx;
		border-bottom-right-radius: 16rpx;
	}
.scroll {
	flex: 1;
	height: 2rpx;
}
.page-bottom-box{
	position: absolute;
	left: 0px;
	bottom: 0px;
	width: 100%;
}
</style>
